import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.template

from data import *

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("./template/index.html")
class ViewHandler(tornado.web.RequestHandler):
    def get(self,username):
        names = get_snippet_names_by_author(username)
        print names
        snippets = [];
        for name in names:
            snippet = get_snippet_by_file(name)
            snippets.append(snippet)
        snippets = snippets[::-1]
        self.render("./template/view.html", username = username, snippets = snippets);
class PostHandler(tornado.web.RequestHandler):
    def post(self):
        title = self.get_argument('title')
        code =  self.get_argument('code')
        author = self.get_argument('author')
        #def __init__(self, title, code, author, datetime=None, cid='', visible=True):
        snippet = CodeSnippet(title, code, author)
        snippet.save()
        

settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
    "cookie_secret": "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
    "xsrf_cookies": True,
}
application = tornado.web.Application([
    (r"/", IndexHandler),
    (r"/view/([a-zA-Z0-9_]+)", ViewHandler),
    (r"/newpost", PostHandler),
    ],**settings)

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8080)
    tornado.ioloop.IOLoop.instance().start()
